package com.huawei.cloud.phone.management.adapter.user;

import com.huawei.cloud.phone.management.adapter.utils.HttpUtils;
import com.huawei.cloud.phone.management.application.user.UserService;
import com.huawei.cloud.phone.management.application.user.dto.LoginInfoDTO;
import com.huawei.cloud.phone.management.application.user.dto.UserDTO;
import com.huawei.cloud.phone.management.common.utils.Constants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Optional;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/user")
public class UserController {
    private final UserService userService;

    /**
     * 用户注册，注册成功后会自动登录
     *
     * @param userDTO 用户信息
     * @return 登录信息
     */
    @PostMapping(value = "/register")
    public LoginInfoDTO register(@Valid @RequestBody UserDTO userDTO) {
        log.info("user register {}", userDTO.getUsername());
        return userService.register(userDTO);
    }

    /**
     * 用户登录
     *
     * @param userDTO 用户信息
     * @return 登录信息
     */
    @PostMapping(value = "/login")
    public LoginInfoDTO login(@Valid @RequestBody UserDTO userDTO) {
        log.info("user login {}", userDTO.getUsername());
        return userService.login(userDTO);
    }

    /**
     * 用户退出登录
     */
    @LoginChecker
    @PostMapping(value = "/logout")
    public void logout() {
        Optional<String> sessionId = HttpUtils.getDataFromHeader(Constants.SESSION_ID);
        if (sessionId.isPresent()) {
            log.info("user logout {}", sessionId.get());
            userService.logout(sessionId.get());
        }
    }

    /**
     * 强制用户退出登录
     */
    @PostMapping(value = "/logout-force")
    public void forceLogout(@RequestBody UserDTO userDTO) {
        log.info("force user {} logout", userDTO.getUsername());
        userService.forceLogout(userDTO.getUsername());
    }
}
